import os.path
import sys
from PyQt5.QtMultimedia import QMediaPlayer, QMediaContent
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel, QVBoxLayout, QWidget, QSystemTrayIcon, \
    QLCDNumber, QMessageBox
from PyQt5.QtGui import QPixmap, QIcon, QDesktopServices, QMovie
from PyQt5.QtCore import Qt, QTimer, QUrl, QRect, QSize

PATH = os.path.dirname(__file__)


def get_path(relative_path, env='pack'):
    if env == 'dev':  # Nuitka 打包后的运行环境
        base_path = os.path.dirname(__file__)  # 获取可执行文件所在目录
    else:
        base_path = os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]), "..", "..", ".."))
        base_path = os.path.join(base_path, 'mayday.app/Contents/Resources')
    return os.path.join(base_path,relative_path)


class MyLabel(QLabel):
    """自定义 QLabel 处理鼠标事件"""

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.setMouseTracking(True)  # 允许 QLabel 追踪鼠标
        self.hand_areas = [
            # 歌曲
            QRect(468, 238, 120, 12), QRect(468, 258, 70, 12), QRect(468, 278, 167, 12), QRect(468, 298, 44, 12),
            QRect(655, 238, 95, 12), QRect(655, 258, 83, 12), QRect(655, 278, 44, 12), QRect(655, 298, 71, 12),
            QRect(781, 238, 84, 12), QRect(781, 258, 123, 12), QRect(781, 278, 109, 12), QRect(781, 298, 57, 12),
            QRect(928, 238, 44, 12), QRect(928, 258, 132, 12), QRect(928, 278, 132, 12),
            QRect(363, 287, 22, 22), QRect(392, 287, 22, 22),
            QRect(512, 648, 45, 52), QRect(557, 648, 45, 52), QRect(602, 648, 45, 52), QRect(647, 648, 45, 52),
            QRect(692, 648, 45, 52), QRect(737, 648, 45, 52)  # hq mv
        ]

    def mouseMoveEvent(self, event):
        """检测鼠标是否进入多个手型区域"""
        label_x, label_y = event.pos().x(), event.pos().y()  # 鼠标在 QLabel 内的坐标
        for area in self.hand_areas:
            if area.contains(label_x, label_y):
                self.setCursor(Qt.PointingHandCursor)  # 变手型
                return
        self.setCursor(Qt.ArrowCursor)  # 恢复默认箭头
        super().mouseMoveEvent(event)


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.playing = False  # 开始默认为不播放
        self.click_sound = QMediaPlayer()
        self.playlist = []

        for i in range(1, 16):
            path = get_path(f'cd_wav/{i:02d}.wav')
            if os.path.exists(path):
                self.playlist.append(path)
            else:
                self.playlist = []
                break
        if len(self.playlist) != 15:
            for i in range(1, 16):
                path = get_path(f'cd_wav/{i:02d}.mp3')
                if os.path.exists(path):
                    self.playlist.append(path)
                else:
                    self.playlist = []
                    break

        if len(self.playlist) != 15:
            QMessageBox.warning(
                None,  # 父窗口（None 表示无父窗口）
                "警告",  # 对话框标题
                f"{get_path('cd/wav')}文件夹中歌曲错误\n"
                "请严格按照以下顺序\n"
                "01.wav\n"
                "02.wav\n"
                "03.wav\n"
                "...\n"
                "14.wav\n"
                "15.wav",  # 对话框内容
                QMessageBox.Ok  # 按钮（默认是 Ok）
            )
            self.close()  # 关闭窗口
            sys.exit()  # 退出程序


        self.current_id = 0
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.update_play_time)
        self.player = QMediaPlayer()
        self.player.positionChanged.connect(self.update_play_time)  # 绑定当前播放时间更新事件
        self.player.mediaStatusChanged.connect(self.auto_next_track)

        # 设置窗口无边框和透明背景
        self.setWindowFlags(Qt.FramelessWindowHint)
        self.setAttribute(Qt.WA_TranslucentBackground, True)
        # 加载图片
        self.image = QPixmap(os.path.join(PATH, 'src/background1.png'))  # 替换为你的图片路径
        self.resize(self.image.size())
        # 创建一个中心部件和布局
        central_widget = QWidget(self)
        self.setCentralWidget(central_widget)
        layout = QVBoxLayout(central_widget)
        layout.setAlignment(Qt.AlignCenter)  # 设置布局内容居中
        # 初始化一个QLabel对象
        self.background = MyLabel(self)
        self.background.setAlignment(Qt.AlignCenter)  # 设置图片在QLabel中居中
        self.background.setPixmap(self.image)
        layout.addWidget(self.background)

        self.playing_label = QLabel(self)
        self.playing_label.setGeometry(234, 249, 66, 30)

        self.gif_label = QLabel(self)
        self.gif_label.setGeometry(554, 442, 209, 108)  # 设置 GIF 显示区域的大小
        self.movie_norm = QMovie(os.path.join(PATH, "src/movie.gif"))
        self.movie_norm.setScaledSize(QSize(209, 108))  # 设置 GIF 的大小
        self.movie_back = QMovie(os.path.join(PATH, "src/back.gif"))
        self.movie_back.setScaledSize(QSize(209, 108))  # 设置 GIF 的大小
        self.movie_go = QMovie(os.path.join(PATH, "src/go.gif"))
        self.movie_go.setScaledSize(QSize(209, 108))  # 设置 GIF 的大小

        self.gif_label.setMovie(self.movie_norm)
        self.movie_norm.start()
        self.movie_norm.stop()

        self.melody_label = QLabel(self)
        self.melody_label.setGeometry(436, 247, 30, 78)
        self.melody_im = QMovie(os.path.join(PATH, "src/jump.gif"))
        self.melody_im.setScaledSize(QSize(30, 78))

        self.pause_button = QLabel(self)
        self.pause_button.setCursor(Qt.PointingHandCursor)
        self.pause_button.setFixedSize(48, 56)
        self.button = QLabel(self)
        self.button.setCursor(Qt.PointingHandCursor)
        self.button.setFixedSize(48, 56)
        self.button_im = QPixmap(os.path.join(PATH, "src/button.jpg")).scaled(48, 56)

        self.start_pause_label = QLabel(self)
        self.start_pause_label.setCursor(Qt.PointingHandCursor)
        self.start_im = QPixmap(os.path.join(PATH, "src/start.jpg"))
        self.pause_im = QPixmap(os.path.join(PATH, "src/pause.jpg"))

        # self.hq_label = QLabel(self)
        # self.hq_label.setFixedSize(31, 31)
        # self.hq_im = QPixmap('hq.jpg').scaled(31, 31)
        # # self.hq_label.setPixmap(self.hq_im)
        #
        # self.mv_label = QLabel(self)
        # self.mv_label.setFixedSize(31, 31)
        # self.mv_im = QPixmap('mv.jpg').scaled(31, 31)

        # 添加一个QLCDNumber到指定位置  353
        self.lcd_no = QLCDNumber(self)
        self.lcd_no.setDigitCount(5)
        self.lcd_no.setGeometry(214, 294, 65, 28)  # 设置位置和大小
        self.lcd_no.display(f"{15:02d}")  # 显示一个数字
        self.lcd_no.setFrameStyle(QLCDNumber.NoFrame)

        self.lcd_time = QLCDNumber(self)
        self.lcd_time.setDigitCount(5)
        self.lcd_time.display("59:59")
        self.lcd_time.setGeometry(290, 294, 65, 28)  # 设置位置和大小
        self.lcd_time.setFrameStyle(QLCDNumber.NoFrame)

        # 将窗口居中显示
        self.center_window()
        self.tray_icon = QSystemTrayIcon(self)
        self.tray_icon.setIcon(QIcon(os.path.join(PATH, 'src/icon.ico')))  # 设置托盘图标
        self.tray_icon.show()

    def center_window(self):
        """将窗口居中显示在屏幕中"""
        screen_geometry = QApplication.primaryScreen().geometry()  # 获取主屏幕的几何信息
        center_point = screen_geometry.center()  # 获取屏幕中心点
        frame_geometry = self.frameGeometry()  # 获取窗口的几何信息
        frame_geometry.moveCenter(center_point)  # 将窗口中心点移动到屏幕中心点
        self.move(frame_geometry.topLeft())  # 移动窗口到计算的位置

    def mousePressEvent(self, event):
        """鼠标按下事件"""
        if event.button() == Qt.LeftButton:
            self.dragging = True  # 开始拖动
            self.offset = event.globalPos() - self.pos()  # 计算鼠标点击位置与窗口位置的偏移

            # 获取点击的坐标位置
            click_pos = event.pos()
            self.pos_list = [
                QRect(480, 250, 120, 12), QRect(480, 270, 70, 12), QRect(480, 290, 167, 12), QRect(480, 310, 44, 12),
                QRect(667, 250, 95, 12), QRect(667, 270, 83, 12), QRect(667, 290, 44, 12), QRect(667, 310, 71, 12),
                QRect(793, 250, 84, 12), QRect(793, 270, 123, 12), QRect(793, 290, 109, 12), QRect(793, 310, 57, 12),
                QRect(940, 250, 44, 12), QRect(940, 270, 132, 12), QRect(940, 290, 132, 12)
            ]

            for i, pos in enumerate(self.pos_list):
                if pos.contains(click_pos):
                    # 清除暂停状态
                    self.pause_button.clear()
                    if self.playing:
                        if i - self.current_id >= 0:
                            self.current_id = i
                            self.current_id -= 1
                            self.next_music()
                        else:
                            self.current_id = i
                            self.current_id += 1
                            self.pre_music()
                    else:
                        self.current_id = i
                        self.start_music()

            # 播放按钮
            if QRect(522, 660, 45, 52).contains(click_pos):
                self.start_music()
            # 暂停按钮
            elif QRect(567, 660, 45, 52).contains(click_pos):
                self.pause_music()
            # 重置按钮
            elif QRect(612, 660, 45, 52).contains(click_pos):
                self.reset_music()
            # 上一首按钮
            elif QRect(657, 660, 45, 52).contains(click_pos):
                self.pre_music()
            # 下一首按钮
            elif QRect(702, 660, 45, 52).contains(click_pos):
                self.next_music()
            # 退出按钮
            elif QRect(747, 660, 45, 52).contains(click_pos):
                self.start_click(wav_path="src/click.wav", music=False, delay=500)
                self.pause_button.clear()
                self.button.setPixmap(self.button_im)
                self.button.move(747, 657)
                self.player.stop()
                self.timer.stop()
                self.delay_timer = QTimer()
                self.delay_timer.singleShot(1000, lambda: self.quit_music())  # 假设 click.wav 时长为 1 秒

            elif QRect(374, 300, 22, 22).contains(click_pos):
                hq_dir = get_path('hq_wav')
                if os.path.exists(hq_dir):
                    QDesktopServices.openUrl(QUrl.fromUserInput(hq_dir))
                else:
                    QMessageBox.warning(
                        None,  # 父窗口（None 表示无父窗口）
                        "警告",  # 对话框标题
                        f"{hq_dir} not exist!",  # 对话框内容
                        QMessageBox.Ok  # 按钮（默认是 Ok）
                    )
            elif QRect(402, 299, 22, 22).contains(click_pos):
                mv_dir = get_path('mv')
                if os.path.exists(mv_dir):
                    QDesktopServices.openUrl(QUrl.fromUserInput(mv_dir))
                else:
                    QMessageBox.warning(
                        None,  # 父窗口（None 表示无父窗口）
                        "警告",  # 对话框标题
                        f"{mv_dir} not exist!",  # 对话框内容
                        QMessageBox.Ok  # 按钮（默认是 Ok）
                    )
    def mouseMoveEvent(self, event):
        """鼠标移动事件"""
        if self.dragging:
            self.move(event.globalPos() - self.offset)  # 移动窗口
        super().mouseMoveEvent(event)

    def mouseReleaseEvent(self, event):
        """鼠标释放事件"""
        if event.button() == Qt.LeftButton:
            self.dragging = False  # 停止拖动

    def update_timer(self):
        self.counter += 1
        self.lcd_second.display(f"{self.counter % 60:02d}")
        self.lcd_minute.display(f"{int(self.counter / 60):02d}")

    def update_play_time(self):
        """更新当前播放时间"""
        current_time = self.player.position() // 1000  # 获取当前播放时间（毫秒转换为秒）
        minutes = current_time // 60
        seconds = current_time % 60
        self.lcd_time.display(f"{minutes:02}:{seconds:02}")

    def play_main_music(self):
        # 播放主音乐
        self.button.clear()
        self.button.setPixmap(self.button_im)
        self.button.move(519, 657)

        self.lcd_no.display(f"{self.current_id + 1:02d}")
        self.player.setMedia(QMediaContent(QUrl.fromUserInput((self.playlist[self.current_id]))))
        self.player.play()
        self.timer.start(1000)  # 启动计时器
        self.change_state()
        self.gif_label.setMovie(self.movie_norm)
        self.movie_norm.start()
        self.melody_label.setMovie(self.melody_im)
        self.melody_im.start()
        im = QPixmap(os.path.join(PATH, 'src/playing.jpg')).scaled(66, 30)
        self.playing_label.setPixmap(im)

    def auto_next_track(self, status):
        if status == QMediaPlayer.EndOfMedia:
            if self.current_id < len(self.playlist) - 1:
                self.current_id += 1
                self.start_click(wav_path=None, music=True, delay=500)

    def start_click(self, wav_path, music, delay):
        if wav_path is not None:
            wav_path = os.path.join(PATH, wav_path)
            # self.click_sound.setSource(QUrl.fromLocalFile(wav_path))
            self.click_sound.setMedia(QMediaContent(QUrl.fromLocalFile(wav_path)))
            self.click_sound.play()
        if music:
            self.delay_timer = QTimer()
            self.delay_timer.singleShot(delay, lambda: self.play_main_music())  # 假设 click.wav 时长为 1 秒

    def start_music(self):
        self.playing = True
        self.start_click(wav_path="src/click.wav", music=True, delay=500)

    def pause_music(self):
        if self.playing:
            # 暂停
            if self.player.state() == QMediaPlayer.PlayingState:
                self.start_click(wav_path="src/click.wav", music=False, delay=500)
                self.player.pause()
                self.timer.stop()
                self.playing_label.clear()
                self.movie_norm.stop()
                self.melody_im.stop()
                self.change_state(pause=True)
                self.pause_button.setPixmap(self.button_im)
                self.pause_button.move(565, 657)
            # 继续
            else:
                self.start_click(wav_path="src/click.wav", music=False, delay=500)
                self.player.play()
                self.timer.start(1000)
                im = QPixmap(os.path.join(PATH, 'src/playing.jpg')).scaled(66, 30)
                self.playing_label.setPixmap(im)
                self.movie_norm.start()
                self.melody_im.start()
                self.change_state()
                self.pause_button.clear()

    def reset_music(self):
        if self.playing:
            self.playing = False
            self.start_click(wav_path="src/click.wav", music=False, delay=500)
            self.current_id = 0
            self.timer.stop()
            self.player.stop()
            self.lcd_no.display(f"{15:02d}")
            self.lcd_time.display(f"59:59")
            self.playing_label.clear()
            self.gif_label.setMovie(self.movie_norm)
            self.movie_norm.start()
            self.movie_norm.stop()
            self.melody_im.stop()
            self.melody_label.clear()
            self.start_pause_label.clear()
            self.button.move(609, 657)
            self.pause_button.clear()
            timer = QTimer()
            timer.singleShot(500, lambda: self.button.clear())

    def pre_music(self):
        if self.playing:
            self.current_id = 14 if self.current_id == 0 else self.current_id - 1
            if self.player.state() == QMediaPlayer.PlayingState:
                self.player.stop()
                self.timer.stop()
            self.button.move(655, 657)
            self.gif_label.setMovie(self.movie_back)
            self.movie_back.start()

            self.start_click(wav_path='src/pre.wav', music=True, delay=1500)

    def next_music(self):
        if self.playing:
            self.current_id = 0 if self.current_id == 14 else self.current_id + 1
            if self.player.state() == QMediaPlayer.PlayingState:
                self.player.stop()
                self.timer.stop()
            self.button.move(701, 657)
            self.gif_label.setMovie(self.movie_go)
            self.movie_go.start()
            self.start_click(wav_path='src/next.wav', music=True, delay=1500)

    def quit_music(self):

        self.tray_icon.hide()  # 隐藏托盘图标
        self.close()  # 关闭窗口
        sys.exit()  # 退出程序

    def change_state(self, pause=False):
        # 设置标记
        if pause:
            self.start_pause_label.setPixmap(self.pause_im)
        else:
            self.start_pause_label.setPixmap(self.start_im)
        self.start_pause_label.move(self.pos_list[self.current_id].x() - 4, self.pos_list[self.current_id].y() - 11)


if __name__ == '__main__':
    """
    python -m nuitka --standalone --onefile --enable-plugin=pyqt5 --macos-create-app-bundle --output-dir=build --assume-yes-for-download --macos-app-version=2.0 --disable-console --include-data-dir=./cd_wav/=./cd_wav/ --include-data-dir=./hq_wav/=./hq_wav/ --include-data-dir=./mv/=./mv/ --include-data-dir=./src/=./src/ --macos-app-icon=./app.icns mayday.py
    
    """
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())
